package com;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Scanner;

public class MainServer {
	public static MainServer main = null;
	private MainClientThread client = null;
	private ServerAccept server = null;
	private ThreadPool threadPool = new ThreadPool();

	public static void main(String[] args) {
		main = new MainServer();
		main.Run(args);
	}

	private void Run(String[] args) {
		int serverPort = 0;
		int clientPort = 0;
		int port = 0;
		String address = "";
		
		try {
			serverPort = Integer.parseInt(getParam(args, "-sp"));
			if (serverPort < 0) throw new Exception();
		} catch (Exception e) {
			System.out.println("Input Server Port Error");
			return;
		}

		try {
			clientPort = Integer.parseInt(getParam(args, "-cp"));
			if (clientPort < 0) throw new Exception();
		} catch (Exception e) {
			System.out.println("Input Client Port Error");
			return;
		}

		try {
			port = Integer.parseInt(getParam(args, "-p"));
			if (port < 0) throw new Exception();
		} catch (Exception e) {
			System.out.println("Input Port Error");
			return;
		}
		try {
			address = getParam(args, "-a");
			if (address.length() < 0) throw new Exception();
		} catch (Exception e) {
			System.out.println("Input Address Port Error");
			return;
		}
		
		try {
			client = new MainClientThread(new ServerSocket(clientPort), threadPool, address, port);
			client.newThreadStrat();
		} catch (IOException e1) {
			System.out.println("Not Open Client Port:" + clientPort);
			return;
		}

		try {
			server = (ServerAccept) new ServerAccept(new ServerSocket(serverPort), threadPool);
			server.setMainClient(client);
			server.newThreadStrat();
		} catch (IOException e1) {
			System.out.println("Not Open Server Port:" + serverPort);
			client.close();
			return;
		}
		
		Scanner in = new Scanner(System.in);
		while (in.hasNext()) {
			if (in.next().equals("exit")) {
				break;
			}
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				System.out.println(e.getMessage());
			}
		}
		threadPool.closeThreadPool();
	}



	private String getParam(String[] args, String key) {
		for (int i = 0; i < args.length; i++) {
			if (args[i].equals(key)) {
				return args[i + 1].trim();
			}
		}
		return "";
	}
}
